import axios, {
	type AxiosRequestConfig,
	type AxiosResponse,
	AxiosError,
} from 'axios'
import type { AxiosInstance } from 'axios'
import {useTokenStore} from '@/store/modules/tokenStore'
import { getDAesString,getEncryptKey } from '@/miniFile/utils/code'

// 响应数据接口
export interface ApiResponse<T = any> {
	code: number
	message: string
	data: T
	success: boolean
}

// 请求配置接口
export interface RequestConfig extends AxiosRequestConfig {
	showLoading?: boolean
	showError?: boolean
}

class Request {
	private instance: AxiosInstance
	private loading: boolean = false

	constructor(config: AxiosRequestConfig) {
		this.instance = axios.create(config)
		this.setupInterceptors()
	}

	private setupInterceptors() {
		// 请求拦截器
		this.instance.interceptors.request.use(
			(config: any) => {
				// 显示加载状态
				if (config.showLoading !== false) {
					this.showLoading()
				}

				// 添加token
				const token = this.getToken()
				if (token) {
					config.headers.token = `${token}`
				}

				// 添加时间戳防止缓存
				if (config.method === 'get') {
					config.params = {
						...config.params,
						_t: Date.now(),
					}
				}

				// console.log('请求发送:', config)
				return config
			},
			(error: AxiosError) => {
				this.hideLoading()
				console.error('请求错误:', error)
				return Promise.reject(error)
			}
		)

		// 响应拦截器
		this.instance.interceptors.response.use(
			(response: AxiosResponse<ApiResponse>) => {
				this.hideLoading()

				const { data,headers } = response
        const dzEncrypt = headers['dz-encrypt'];
        
      
				// 根据业务状态码处理
				if (response.status === 200 || data.success) {
          // 解密
        if (dzEncrypt==1) {
          const myRecommendCode = useTokenStore()?.userInfo.recommendCode;
          if(myRecommendCode) {
            
          const key = getEncryptKey(myRecommendCode);
          const iv = getEncryptKey(myRecommendCode, true);
  
          // console.log("解密前的数据：", response.data);
  
          const dData = getDAesString(data, key, iv);
  
          console.log("解密后的数据：", dData);
          try {
            response.data = JSON.parse(dData)
          } catch(e) {
            response.data = dData;
          }
          return response
        }
        }
					// 修改response.data为业务数据，保持AxiosResponse结构
					response.data = data
					return response
				} else {
					// 业务错误
					this.handleBusinessError(data)
					return Promise.reject(new Error(data.message || '请求失败'))
				}
			},
			(error: AxiosError) => {
				this.hideLoading()
				this.handleHttpError(error)
				return Promise.reject(error)
			}
		)
	}

	// 获取token
	private getToken(): string | null {
		return localStorage.getItem('token') || sessionStorage.getItem('token')
	}

	// 显示加载状态
	private showLoading() {
		if (!this.loading) {
			this.loading = true
			// 这里可以集成你的loading组件
			console.log('显示loading...')
		}
	}

	// 隐藏加载状态
	private hideLoading() {
		if (this.loading) {
			this.loading = false
			// 这里可以集成你的loading组件
			console.log('隐藏loading...')
		}
	}

	// 处理业务错误
	private handleBusinessError(data: ApiResponse) {
		const { code, message } = data

		switch (code) {
			case 401:
				// 未授权，清除token并跳转登录
				this.clearAuth()
				this.redirectToLogin()
				break
			case 403:
				console.error('权限不足:', message)
				break
			case 404:
				console.error('资源不存在:', message)
				break
			case 500:
				console.error('服务器错误:', message)
				break
			default:
				console.error('业务错误:', message)
		}

		// 显示错误提示
		this.showError(message || '请求失败')
	}

	// 处理HTTP错误
	private handleHttpError(error: AxiosError) {
		let message = '网络错误'

		if (error.response) {
			const { status } = error.response
			switch (status) {
				case 400:
					message = '请求参数错误'
					break
				case 401:
					message = '未授权，请重新登录'
					this.clearAuth()
					this.redirectToLogin()
					break
				case 403:
					message = '权限不足'
					break
				case 404:
					message = '请求的资源不存在'
					break
				case 500:
					message = '服务器内部错误'
					break
				case 502:
					message = '网关错误'
					break
				case 503:
					message = '服务不可用'
					break
				case 504:
					message = '网关超时'
					break
				default:
					message = `请求失败 ${status}`
			}
		} else if (error.request) {
			message = '网络连接失败'
		}

		console.error('HTTP错误:', error)
		this.showError(message)
	}

	// 清除认证信息
	private clearAuth() {
		localStorage.removeItem('token')
		sessionStorage.removeItem('token')
		localStorage.removeItem('userInfo')
	}

	// 跳转到登录页
	private redirectToLogin() {
		// 这里可以集成你的路由跳转逻辑
		console.log('跳转到登录页...')
		// window.location.href = '/login'
	}

	// 显示错误信息
	private showError(message: string) {
		// 这里可以集成你的消息提示组件
		console.error('错误提示:', message)
		// 例如: ElMessage.error(message)
	}

	// GET请求
	get<T = any>(
		url: string,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		return this.instance.get(url, config)
	}

	// POST请求
	post<T = any>(
		url: string,
		data?: any,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		return this.instance.post(url, data, config)
	}

	// PUT请求
	put<T = any>(
		url: string,
		data?: any,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		return this.instance.put(url, data, config)
	}

	// DELETE请求
	delete<T = any>(
		url: string,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		return this.instance.delete(url, config)
	}

	// PATCH请求
	patch<T = any>(
		url: string,
		data?: any,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		return this.instance.patch(url, data, config)
	}

	// 上传文件
	upload<T = any>(
		url: string,
		file: File,
		config?: RequestConfig
	): Promise<AxiosResponse<ApiResponse<T>>> {
		const formData = new FormData()
		formData.append('file', file)

		return this.instance.post(url, formData, {
			...config,
			headers: {
				'Content-Type': 'multipart/form-data',
				...config?.headers,
			},
		})
	}

	// 下载文件
	download(
		url: string,
		filename?: string,
		config?: RequestConfig
	): Promise<void> {
		return this.instance
			.get(url, {
				...config,
				responseType: 'blob',
			})
			.then((response: any) => {
				const blob = new Blob([response.data])
				const downloadUrl = window.URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = downloadUrl
				link.download = filename || 'download'
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				window.URL.revokeObjectURL(downloadUrl)
			})
	}
}

// 创建默认实例（主 API）
export const request = new Request({
	baseURL: '', // 使用代理路径
	timeout: 10000,
	headers: {
		'Content-Type': 'application/json',
	},
})

// 创建微信 API 实例
export const wxRequest = new Request({
	baseURL: '/wx-api', // 使用代理路径
	timeout: 15000,
	headers: {
		'Content-Type': 'application/json',
	},
})

// 创建上传服务实例
export const uploadRequest = new Request({
	baseURL: '/upload', // 使用代理路径
	timeout: 30000, // 上传文件超时时间较长
})

// 创建支付 API 实例
export const payRequest = new Request({
	baseURL: '/pay-api', // 使用代理路径
	timeout: 10000,
	headers: {
		'Content-Type': 'application/json',
	},
})

// 创建静态资源实例
export const staticRequest = new Request({
	baseURL: '/static', // 使用代理路径
	timeout: 5000,
})
